package my.org.swing.date;

import java.awt.BorderLayout;
import java.awt.Component;
import java.time.LocalDate;
import javax.swing.JButton;
import javax.swing.JComponent;

public class DateField extends JComponent implements DateObserver {

    private static final long serialVersionUID = -4645837000641452612L;

    private DateWindow window;

    private LocalDate selectedDate;

    protected JButton btn = new JButton("...");

    public DateField() {
        setLayout(new BorderLayout());
        add(btn);

        btn.addActionListener(e -> {
            int x = (int) btn.getLocationOnScreen().getX();
            int y = (int) btn.getLocationOnScreen().getY() + btn.getHeight() + 1;
            getDateWindow().showMe(x, y);
        });
    }

    @Override
    public void dateChanged(LocalDate dateTime) {
        selectedDate = dateTime;
        btn.setText(dateTime.toString());
    }

    public LocalDate getSelectedDate(){
        return selectedDate;
    }

    @Override
    public Component getComponent() {
        return this;
    }

    public DateWindow getDateWindow() {
        if (window == null) {
            window = new DateWindow(DateField.this, null);
        }

        return window;
    }

    public void clearOldWindow() {
        if (window != null) {
            window.dispose();
        }
        window = null;
    }
}
